import { Injectable } from "@nestjs/common";
import { InjectRedis, Redis } from "@nestjs-modules/ioredis";
import { isEmpty } from "lodash";
import { USER_TOKEN_KEY, USER_VERSION_KEY } from "src/common/constants/redis.constant";
import { ApiException } from "src/common/exceptions/api.exception";
import { UserService } from "../user/user.service";
import { SharedService } from "src/shared/shared.service";

@Injectable()
export class AuthService {
  constructor(
    @InjectRedis() private readonly redis: Redis,
    private readonly userService: UserService,
    private readonly sharedService: SharedService,
  ) {}

  /**
   * @description: 判断token 是否过期 或者被重置
   * @param {number} userId
   * @param {number} pv
   * @param {string} restoken
   * @return {*}
   */
  async validateToken(userId: number, pv: number, restoken: string) {
    const token = await this.redis.get(`${USER_TOKEN_KEY}:${userId}`);
    if (restoken !== token) throw new ApiException("登录状态已过期啦", 401);
    const passwordVersion = parseInt(await this.redis.get(`${USER_VERSION_KEY}:${userId}`));
    if (pv !== passwordVersion) throw new ApiException("用户信息已被修改", 401);
  }

  /**
   * @description: 判断用户名和密码是否正确
   * @param {string} username
   * @param {string} password
   * @return {*}
   */
  async validateUser(username: string, password: string) {
    // const salt = this.sharedService.generateUUID();
    // const password1 = this.sharedService.md5("admin" + salt);
    // console.log("aaaa: ", password1, salt);

    const user = await this.userService.findOneByUsername(username);
    if (!user) throw new ApiException("用户名或密码错误");
    const comparePassword = this.sharedService.md5(password + user.salt);
    if (comparePassword !== user.password) throw new ApiException("用户名或密码错误");
    return user;
  }
}
